package controllers

import (
	"beego/comm/algorithm"
	"beego/comm/auth"
	"beego/comm/utils"
	"fmt"
	"strings"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type QueryBdndFileController struct {
	beego.Controller
}

func (c *QueryBdndFileController) QueryBdndFile() {
	beego.Info("================= QueryBdndFile start =================")
	result := map[string]interface{}{
		"data":  "",
		"error": "",
	}
	c.Data["json"] = result
	defer func() {
		err := recover()
		if nil != err {
			result["error"] = err
			c.ServeJSON()
		}
	}()
	resp := auth.HandleLogin(c.Ctx.Input.RequestBody)
	queryStr := utils.CheckFieldExists(resp, "keys").(string)
	queryArr := strings.Split(queryStr, " ")
	var query_arr []string
	for _, v := range queryArr {
		if v != "" {
			query_arr = append(query_arr, v)
		}
	}
	perm := algorithm.Permutation(len(query_arr))
	var where_arr []string
	for _, i := range perm {
		var tmp []string
		for _, j := range i {
			tmp = append(tmp, query_arr[j])
		}
		tmp_str := strings.Join(tmp, ".*")
		where_arr = append(where_arr, tmp_str)
	}
	var sub_select_arr []string
	for _, i := range where_arr {
		tmp := fmt.Sprintf("select * from sivan.bdy_path bp where `path` regexp '%s'", i)
		sub_select_arr = append(sub_select_arr, tmp)
	}
	sql := strings.Join(sub_select_arr, " UNION\n")
	beego.Info("\n" + sql)
	o := orm.NewOrm()
	var maps []orm.Params
	o.Raw(sql).Values(&maps)
	if maps == nil {
		maps = []orm.Params{}
	}
	for id, value := range maps {
		value["id"] = fmt.Sprintf("%d", id)
	}
	result["data"] = maps
	c.ServeJSON()
	beego.Info("================= QueryBdndFile end =================")
}
